﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Communication
{
    public partial class ctrlTCPLogger : UserControl
    {

        private TCPIPSocket _loggerSocket = null;
        private string _receivedData = string.Empty;


        public ctrlTCPLogger()
        {
            InitializeComponent();

            this._loggerSocket = new TCPIPSocket("127.0.0.1", 9470, textBoxID.Text);
            this._loggerSocket.TCPTransmissionReceived += LoggerSocket_TCPTransmissionReceived;
        }

        private void PublishMessageInControl()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(PublishMessageInControl));
            else
            {
                this.listBoxLogging.Items.Add(this._receivedData);
            }
        }

        private void LoggerSocket_TCPTransmissionReceived(string text)
        {
            this._receivedData = text;
            this.PublishMessageInControl();
        }

        public bool IsConnected
        {
            get { return this._loggerSocket.IsConnected; }
        }

        public void Disconnect()
        {
            if (this.IsConnected)
            {
                this._loggerSocket.Disconnect();
            }
        }


        private void buttonSend_Click(object sender, EventArgs e)
        {
            this._loggerSocket.SendData(this.textBoxMessage.Text);
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (this._loggerSocket.IsConnected)
            {
                this._loggerSocket.Disconnect();
            } else
            {
                this._loggerSocket.Connect();
            }
        }
    }
}
